//
//  SceneryViewController.m
//  lv678
//
//  Created by apple on 15/6/11.
//  Copyright (c) 2015年 lampshade. All rights reserved.
//
/**
 *  判断是哪个版本
 *
 *  @param > systemVersion
 *
 *  @return bool
 */
#define IS_IOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
#define IS_IOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8)

#import "SceneryViewController.h"
#import "CCLocationManager.h"
#import "AFNetworking.h"
#import "SceneryListModel.h"
#import "SceneryCell.h"
#import "MJRefresh.h"
#import "SceneryDetailController.h"
#import "CommonLoading.h"

@interface SceneryViewController ()<CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UISearchBar *searchCityName;//搜索框


@property (nonatomic, strong) CLLocationManager *locationManager;//定位
@property (nonatomic, copy) NSString *cityName;//城市名称
@property (nonatomic, assign) int i;//加载页数变量
@property (nonatomic,assign) int count;//景点总条数
@property (nonatomic, strong) UIView *waitView;//家在试图
@property (nonatomic, strong) NSMutableArray *sceneryArry;//景点可变数组
@property (nonatomic, strong) UIView *noDataTip;//错误提示视图
@property (nonatomic, copy) NSString  *city;

@end

@implementation SceneryViewController
@synthesize locationManager;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController setNavigationBarHidden:NO animated:true];
    
    [self initTableView];
}
#pragma mark - 初始化tableview
- (void)initTableView{
    
    UIView *noDataTips = [[CommonLoading initCommonLoading]noDataTips];
    self.noDataTip = noDataTips;
    
    self.sceneryArry = [NSMutableArray array];
    
    self.searchCityName.delegate = self;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //隐藏单元格分割线
    self.tableView.separatorStyle = NO;
    
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    
    UIColor *color = [UIColor whiteColor];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    [self.navigationController.navigationBar setTitleTextAttributes:dict];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Navigation"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    //自定义等待视图
    UIView *waitView = [[UIView alloc]initWithFrame:CGRectZero];
    waitView = [[CommonLoading initCommonLoading]refreshLoading];
    self.waitView = waitView ;
    [self.tableView addSubview:waitView];

    
    if (IS_IOS8) {
        [UIApplication sharedApplication].idleTimerDisabled =  TRUE;
        locationManager = [[CLLocationManager alloc]init];
        [locationManager requestWhenInUseAuthorization];
        locationManager.delegate = self;
    }
    [self getCityName];
}

- (void)upRefresh{
    self.i++;
    [self.tableView.footer beginRefreshing];
    if (self.sceneryArry.count == self.count) {
        [self.tableView.footer noticeNoMoreData];
        
    }
    [self getData:self.cityName index:self.i];
}

#pragma mark - 根据经纬度获取城市名称
- (void)getCityName{
    self.i = 1;
    if (IS_IOS8) {
        [[CCLocationManager shareLocation]getCity:^(NSString *cityString) {
            self.cityName = [cityString substringToIndex:cityString.length-1];
            if ([self.cityName isEqualToString:@""] && self.cityName.length == 0) {
                [self.waitView removeFromSuperview];
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"定位失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }else{
            [self getData:self.cityName index:self.i];
            }
        }];
    }

}

#pragma mark - 根据城市名称获取景点
- (void)getData:(NSString *)cityName index:(int)i{
    
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"UrlList.plist" ofType:nil];
    NSDictionary *temp = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *url = [temp objectForKey:@"viewspotapp"];
    NSString *index = [NSString stringWithFormat:@"%d",i];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer  = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    NSDictionary *data = @{@"serviceName":@"TicketSenicSpotSearch",@"queryParameters":
                               @{@"keywords":cityName,@"PageSize":@"1",@"cityName":cityName,@"DistributionChannel":@"9",@"PageIndex":index}};
    
    [manager POST:url parameters:data success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.tableView.separatorStyle = YES;
        [self.view endEditing:YES];
        NSArray *dic = [[[responseObject objectForKey:@"node1josn"]objectForKey:@"ScenicSpotListItemList"]objectForKey:@"ScenicSpotListItemDTO"];
        for (NSDictionary *dict in dic) {
            SceneryListModel *model = [SceneryListModel sceneryWithDict:dict];
            [self.sceneryArry addObject:model];
        }
        self.count = [[[[[responseObject objectForKey:@"node1josn"]objectForKey:@"TabTypeSatistics"]valueForKey:@"TabTypeSatistics"]valueForKey:@"Count"]intValue];
        [self.tableView.footer endRefreshing];
        [self.tableView reloadData];
        [self.waitView removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.sceneryArry removeAllObjects];
        [self.tableView reloadData];
        [self.waitView removeFromSuperview];
        [self.view endEditing:YES];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.tableView addSubview:self.noDataTip];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.sceneryArry.count == 0) {
        return 0;
    }else{
    return self.sceneryArry.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return 110;
}

#pragma mark - TableView单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identity = @"SceneryCell";
    SceneryListModel *model = self.sceneryArry[indexPath.row];
    SceneryCell *cell = [tableView dequeueReusableCellWithIdentifier:identity];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"SceneryCell" owner:self options:nil]lastObject];
    }
    [cell setModel:model];
    return cell;
}
#pragma mark - 点击单元格触发的事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SceneryListModel *model = self.sceneryArry[indexPath.row];
    SceneryDetailController *detail = [[SceneryDetailController alloc]init];
    detail.detailModel = model;
    [self.navigationController pushViewController:detail animated:YES];
    
}

#pragma mark - searchBarController代理实现
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.noDataTip removeFromSuperview];
    if ([self.city isEqualToString:@""]) {
        self.cityName = self.cityName;
    }else{
        self.cityName = self.city;
    }
    [self.sceneryArry removeAllObjects];
    
    [self getData:self.cityName index:self.i];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self.noDataTip removeFromSuperview];
    self.city = searchText;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    [self.sceneryArry removeAllObjects];
    [self.tableView reloadData];
    self.tableView.separatorStyle = NO;
    [self.tableView addSubview:self.waitView];
}

#pragma mark - 滚动视图关闭软键盘
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.searchCityName resignFirstResponder];
}

//#pragma mark - 设置状态栏为高亮
//-(UIStatusBarStyle)preferredStatusBarStyle
//{
//    NSLog(@"sdfdfdfdfdfd");
//    return UIStatusBarStyleLightContent;
//}
@end
